// pages/city/city.js
import AMap from '../../utils/amap-wx.130.js';
const alphabetCity = require('../../utils/alphabetCity.js').alphabetCity;
const map = new AMap.AMapWX({
	key: '96fbfbfa0da8105bae93ac83ff911c2c'
});
Page({
	/**
	 * 页面的初始数据
	 */
	data: {
		currentCity: '',  		//当前所选城市
		location: '',           //当前定位城市
		accurate: false,        //开启区县选择
		areaSelect: [],         //区县选择数据
		lately: [],             //"最近访问" 数据
		latelyMaxNum: 5,		//"最近访问" 上限条数
		alphabetCity: {},       //城市列表
		search: '',             //搜索的内容
		searchList: [],         //搜索的结果数据
	},

	/**
	 * 生命周期函数--监听页面加载
	 */
	onLoad: function (options) {
		this.geolocation();
		this.initLatelyCity();
		this.setData({
			alphabetCity,
			currentCity: wx.getStorageSync('alpCity')
		});

		// wx.removeStorageSync('lately');
	},
	//获取当前城市信息
	geolocation(){
		this.setData({ location: 'load'});
		map.getRegeo({
			success: res => {
				let location = res[0].regeocodeData.addressComponent.city;
				console.log(`当前位置(${location}):`, res[0]);
				this.setData({
					location
				});
			},
			fail: err => {
				console.log('Error getRegeo:', err);
				this.setData({ location: ''});
				if(err.errMsg == 'getLocation:fail auth deny'){
					this.exception();
				} else {
					wx.getSetting({
						success: res => {
							// console.log('get set:', res);
							if(!res.authSetting['scope.userLocation']){
								this.exception();
							}
						}
					})
				}
			}
		})
	},
	//未授权的异常处理
	exception(){
		wx.showModal({
			title: '温馨提示',
			content: '检测到您 未授权 "获取定位信息"，因此定位功能暂不可用！',
			confirmText: '去开启',
			success: res => {
				if(res.confirm){
					wx.openSetting({
						withSubscriptions: true,
						success: res => {
							console.log('openSetting:', res);
							if(res.authSetting['scope.userLocation']){
								this.geolocation();
							}
						},
						fail(err){
							console.log('Error openSetting:', err);
						}
					});
				}
			}
		})
	},
	//初始化 "最近访问" 数据
	initLatelyCity(city){
		let lately = wx.getStorageSync('lately') || [];
		if(city){
			let index = lately.indexOf(city);
			if(index != -1) lately.splice(index, 1);
			lately.unshift(city);
			lately = lately.slice(0, this.data.latelyMaxNum);
			wx.setStorageSync('lately', lately);
			wx.setStorageSync('alpCity', city);
		}
		this.setData({ lately});
	},
	//选择定位城市
	checkCity(e){
		let currentCity = e.currentTarget.dataset.city;
		this.initLatelyCity(currentCity);
		this.setData({ currentCity});
		this.quit();
	},
	//搜索城市
	searchData(e){
		let search = e.detail,
			alphabet = /^[a-zA-Z]*$/.test(search),	//判断是否是字母
			searchList = [];
		if(alphabet) search = search.toLowerCase();	//转小写
		for(let alp in this.data.alphabetCity){
			let data = this.data.alphabetCity[alp];
			data.map(item => {
				let text = alphabet ? item.pinyin.split(' ').join('') : item.text;
				if(text.indexOf(search) != -1){
					searchList.push(item);
				}
			})
		}
		this.setData({ 
			search,
			searchList
		});
	},
	//返回
	quit(){
		wx.navigateBack({
		  	delta: 0,
		})
	}
})